package com.cw.jeeyt.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.cw.lang.common.log.Log;
import com.cw.lang.common.log.TenantLog;

/**
 * 登录成功处理类
 *
 * @author: chenw
 * @create: 2018-11-08 13:44
 */
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static Log log = TenantLog.getLogger(MyAuthenticationSuccessHandler.class);
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException {
        //这里可以根据实际情况，来确定是跳转到页面或者json格式。
        //如果是返回json格式，那么我们这么写
        Map<String, Object> map = new HashMap<>();
        map.put("code", "200");
        map.put("msg", "登录成功");
        map.put("success", true);
        map.put("url", "/system/index");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter()
            .write(objectMapper.writeValueAsString(map));
        log.info("【{}】登录成功", JSON.toJSONString(authentication.getPrincipal()));
        //super.onAuthenticationSuccess(request, response, authentication);
        //response.getWriter().print(GsonUtil.objectToJsonString(map));
        //如果是要跳转到某个页面的，比如我们的那个whoim的则
        //new DefaultRedirectStrategy().sendRedirect(request, response, "/system/index");
    }
}
